/**
 * Created by ltx on 2019/7/2.
 */
const express = require('express');
const mysql = require('mysql');
const common = require('../../libs/common');
const passport = require("passport");

var db = mysql.createPool({ host: 'localhost', user: 'root', password: '123456', database: 'hdadmin' });

module.exports = function () {
  var router = express.Router();

  //$route GET /admin/getroles
  //desc   获取所有角色信息
  //access Private jwt
  router.get('/getroles', passport.authenticate("jwt", { session: false }), (req, res) => {
    res.json({
      id: req.user[0].GUID,
      name: req.user[0].admin_name,
      role: req.user[0].admin_ownrole
    })
  });

  //$route GET /admin/menus
  //desc   获取所有菜单栏
  //access Private jwt
  router.get('/menu', passport.authenticate("jwt", { session: false }), (req, res) => {
    res.json(
      {
        "status": "success",
        "code": 200,
        "children": [{
          "id": "11",
          "parentId": "1",
          "url": "/admin/workbench",
          "name": "工作视图",
          "sequence": 1,
          "icon": "news",
          "children": []
        },
        {
          "id": "12",
          "parentId": "1",
          "url": "application",
          "name": "应用中心",
          "sequence": 2,
          "icon": "sort",
          "children": [{
            "id": "121",
            "parentId": "12",
            "url": "/admin/center",
            "name": "文章中心",
            "sequence": 1,
            "icon": "record",
            "children": [{
              "id": "43f9ec66f37b4379959c9922c593692a",
              "parentId": "121",
              "url": "/admin/markdown",
              "name": "markDown",
              "sequence": 1,
              "icon": "edit",
              "children": []
            },
            {
              "id": "1212",
              "parentId": "121",
              "url": "/admin/edit",
              "name": "富文本",
              "sequence": 1,
              "icon": "edit",
              "children": []
            },
            {
              "id": "1213",
              "parentId": "121",
              "url": "/admin/articlemanage",
              "name": "文章管理",
              "sequence": 1,
              "icon": "edit",
              "children": []
            }
            ]
          },
          {
            "id": "123",
            "parentId": "12",
            "url": "/admin/messages",
            "name": "消息中心",
            "sequence": 3,
            "icon": "mail",
            "children": []
          }
          ]
        },
        {
          "id": "13",
          "parentId": "1",
          "url": "/admin/user",
          "name": "用户管理",
          "sequence": 3,
          "icon": "group",
          "children": []
        }
        ]
      }
    )
  });

  //$route POST /admin/creatnewmessage
  //desc   新增推送消息（系统内部）
  //access Public
  router.post('/creatnewmessage', (req, res) => {
    var username = req.body.username;
    var message = req.body.message;
    var creattime = req.body.creattime;
    db.query(`INSERT INTO system_message (who_sendmessage,message_content,send_time,is_read,is_del,is_real_del) VALUES ('${username}','${message}','${creattime}','N','N','N')`, (err, data) => {
      if (err) {
        res.status(500).send('数据库错误').end();
      }
      else {
        res.json({
          code: 200,
          message: '新增成功！',
          status: "success"
        });
        return;
      }
    })
  });

  //$route GET /admin/getmessagenotread
  //desc   未读消息
  //access Public
  router.get('/getmessagenotread', (req, res) => {
    db.query(`SELECT * FROM system_message where is_read='N' AND is_del ='N' ANd is_real_del ='N'`, (err, data) => {
      if (err) {
        res.status(500).send('数据库错误').end();
      }
      else {
        res.json({
          status: "success",
          data: data
        }).end();
      }
    })
  });

  //$route GET /admin/getmessagealreadyread
  //desc   已读消息
  //access Public
  router.get('/getmessagealreadyread', (req, res) => {
    db.query(`SELECT * FROM system_message where is_read !='N' AND is_del ='N' ANd is_real_del ='N'`, (err, data) => {
      if (err) {
        res.status(500).send('数据库错误').end();
      }
      else {
        res.json({
          status: "success",
          data: data
        }).end();
      }
    })
  });

  //$route GET /admin/getmessageisdel
  //desc   回收站消息
  //access Public
  router.get('/getmessageisdel', (req, res) => {
    db.query(`SELECT * FROM system_message where is_read !='N' AND is_del !='N' ANd is_real_del ='N'`, (err, data) => {
      if (err) {
        res.status(500).send('数据库错误').end();
      }
      else {
        res.json({
          status: "success",
          data: data
        }).end();
      }
    })
  });

  //$route POST /admin/readthemessage
  //desc   改变未读消息状态
  //access Public
  router.post('/readthemessage', (req, res) => {
    var ID = req.query.ID;
    db.query(`UPDATE system_message SET is_read = 'Y' WHERE ID IN (${ID})`, (err, data) => {
      if (err) {
        res.status(500).send('数据库错误').end();
      }
      else {
        res.send(data).end();
      }
    })
  });

  //$route POST /admin/delthemessage
  //desc   把已过期消息放入回收站
  //access Public
  router.post('/delthemessage', (req, res) => {
    var ID = req.body.ID;
    console.log(req.body);
    db.query(`UPDATE system_message SET is_read = 'Y',is_del = 'Y' WHERE ID IN (${ID})`, (err, data) => {
      if (err) {
        res.status(500).send('数据库错误').end();
      }
      else {
        db.query(`SELECT * FROM system_message where is_read !='N' AND is_del ='N' ANd is_real_del ='N'`, (err, data) => {
          if (err) {
            res.status(500).send('数据库错误').end();
          }
          else {
            res.send(data).end();
          }
        })
      }
    })
  });

  //$route POST /admin/delthemessage
  //desc   回收信息
  //access Public
  router.post('/returnthemessage', (req, res) => {
    var ID = req.body.ID;
    db.query(`UPDATE system_message SET is_read = 'Y',is_del = 'N' WHERE ID IN (${ID})`, (err, data) => {
      if (err) {
        res.status(500).send('数据库错误').end();
      }
      else {
        res.send(data).end();
      }
    })
  });

  //$route POST /admin/delallmessage
  //desc   把消息全部放入回收站
  //access Private
  router.post('/delallmessage',passport.authenticate("jwt", { session: false }), (req, res) => {
    db.query(`UPDATE system_message SET is_del = 'Y' WHERE is_read = 'Y' AND is_del = 'N'`, (err, data) => {
      if (err) {
        res.status(500).send('数据库错误').end();
      }
      else {
        res.json({
          message:"删除成功。",
          status: "success",
          code:200
        })
      }
    })
  });

  //$route POST /admin/delallmessage
  //desc   把消息全部标记为已读
  //access Private
  router.post('/readallthemessage',passport.authenticate("jwt", { session: false }), (req, res) => {
    db.query(`UPDATE system_message SET is_read = 'Y' WHERE is_read = 'N' AND is_del = 'N'`, (err, data) => {
      if (err) {
        res.status(500).send('数据库错误').end();
      }
      else {
        res.json({
          message:"全部已读成功。",
          status: "success",
          code:200
        })
      }
    })
  });

  //$route POST /admin/clearallmessage
  //desc   把回收站消息清除
  //access Private
  router.post('/clearallmessage',passport.authenticate("jwt", { session: false }), (req, res) => {
    db.query(`DELETE FROM system_message WHERE is_del = 'Y'`, (err, data) => {
      if (err) {
        res.status(500).send('数据库错误').end();
      }
      else {
        res.json({
          message:"批量删除成功。",
          status: "success",
          code:200
        })
      }
    })
  });

  //$route POST /admin/markdowndata
  //desc   更新储存markdown编辑内容，给标志位
  //access Public
  router.post('/markdowndata', (req, res) => {
    var currentid = req.body.id;
    var markdata = req.body.markdata;
    var username = req.body.username;
    var creattime = req.body.creattime;
    db.query(`UPDATE markdown_table SET admin_name='${username}',article_content='${markdata}',admin_sendtime='${creattime}',is_del='N',mark_state='正常' WHERE ID='${currentid}'`, (err, data) => {
      if (err) {
        res.status(500).send('数据库错误').end();
      }
      else {
        res.json({
          code: 200,
          message: '更新成功！',
          status: 'success'
        });
      }
    })
  });

  //$route POST /admin/addmarkdata
  //desc   新增markdown文章
  //access Public
  router.post('/addmarkdata', (req, res) => {
    var markdata = req.body.markdata;
    var username = req.body.username;
    var creattime = req.body.creattime;
    db.query(`INSERT INTO markdown_table (admin_name,article_content,admin_sendtime,is_del,mark_state) VALUES ('${username}','${markdata}','${creattime}','N','正常')`, (err, data) => {
      if (err) {
        res.status(500).send('数据库错误').end();
      }
      else {
        res.json({
          code: 200,
          message: '新增成功！',
          status: 'success'
        });
      }
    })
  });

  //$route POST /admin/getallmarknum
  //desc   获取mark文章总条数做分页
  //access Public
  router.post('/getallmarknum', (req, res) => {
    db.query(`SELECT COUNT(*) FROM markdown_table WHERE is_del != 'Y'`, (err, data) => {
      if (err) {
        res.status(500).send('数据库错误').end();
      }
      else {
        res.json({
          code: 200,
          num: data[0],
          status: "success"
        });
        return;
      }
    })
  });

  //$route POST /admin/getallmark
  //desc   分页获取mark文章
  //access Public
  router.post('/getallmark', (req, res) => {
    var page = parseInt(req.body.page);
    db.query(`SELECT ID,admin_name,admin_sendtime,article_type,is_del,mark_state,user_sees FROM markdown_table where ID > (${page}-1)*${10} AND is_del !='Y' limit ${10}; `, (err, data) => {
      if (err) {
        res.status(500).send('数据库错误').end();
      }
      else {
        res.json({
          data: data,
          status: "success"
        })
      }
    })
  });

  //$route POST /admin/findsearchmarkresult
  //desc   mark文章管理搜索返回
  //access Public
  router.post('/findsearchmarkresult', (req, res) => {
    var mainwords = req.body.mainwords;
    db.query(`SELECT * FROM markdown_table where admin_name LIKE '%${mainwords}%' OR article_content LIKE '%${mainwords}%' limit ${100}; `, (err, data) => {
      if (err) {
        res.status(500).send('数据库错误').end();
      }
      else {
        res.json({
          status: "success",
          data: data
        });
      }
    })
  });

  //$route POST /admin/editeonemark
  //desc   某一篇mark文章详情
  //access Public
  router.post('/editeonemark', (req, res) => {
    var currentid = req.body.currentid;
    db.query(`SELECT article_content FROM markdown_table where ID=${currentid}`, (err, data) => {
      if (err) {
        res.status(500).send('数据库错误').end();
      }
      else {
        res.json({
          status: "success",
          data: data
        });
      }
    })
  });

  //$route POST /admin/disableonemark
  //desc   禁用单篇文章
  //access Public
  router.post('/disableonemark', (req, res) => {
    var indexID = req.body.indexID;
    var state = req.body.state;
    console.log(req.body);
    if (state == '已禁用') {
      db.query(`UPDATE markdown_table SET mark_state='正常' WHERE ID='${indexID}'`, (err, data) => {
        if (err) {
          res.status(500).send('数据库错误').end();
        }
        else {
          res.json({
            status: 'success',
            message: "操作成功。"
          }).end();
        }
      })
    } else {
      db.query(`UPDATE markdown_table SET mark_state='已禁用' WHERE ID='${indexID}'`, (err, data) => {
        if (err) {
          res.status(500).send('数据库错误').end();
        }
        else {
          res.json({
            status: 'success',
            message: "操作成功。"
          }).end();
        }
      })
    }
  });

  //$route POST /admin/delonemark
  //desc   假删除单篇mark文章
  //access Public
  router.post('/delonemark', (req, res) => {
    var indexID = req.body.indexID;
    db.query(`UPDATE markdown_table SET is_del='Y' WHERE ID='${indexID}'`, (err, data) => {
      if (err) {
        res.status(500).send('数据库错误').end();
      }
      else {
        res.json({
          code: 200,
          status: 'success',
          message: '删除成功！'
        });
        return;
      }
    })
  });

  //$route POST /admin/delmoremark
  //desc   批量假删除mark文章
  //access Public
  router.post('/delmoremark', (req, res) => {
    var indexIDs = req.body.indexIDs;
    console.log(indexIDs);
    db.query(`UPDATE markdown_table SET is_del = 'Y' WHERE ID IN (${indexIDs})`, (err, data) => {
      if (err) {
        res.status(500).send('数据库错误').end();
      }
      else {
        res.json({
          code: 200,
          status: 'success',
          message: '删除成功！'
        });
        return;
      }
    })
  });

  //$route POST /admin/getallusers
  //desc   得到所有用户
  //access Private
  router.post('/getallusers', passport.authenticate("jwt", { session: false }),(req, res) => {
    var page = parseInt(req.body.page);
    db.query(`SELECT * FROM user_table where user_ID > (${page}-1)*${10} AND is_del !='Y' limit ${10}; `, (err, data) => {
      if (err) {
        res.status(500).send('数据库错误').end();
      }
      else {
        res.json({
          status: "success",
          data:data
        })
      }
    })
  });

  //$route GET /admin/getallusersnum
  //desc   得到所有用户数量，做分页总数。
  //access Public
  router.get('/getallusersnum', (req, res) => {
    db.query(`SELECT COUNT(*) FROM user_table WHERE is_del != 'Y'`, (err, data) => {
      if (err) {
        res.status(500).send('数据库错误').end();
      }
      else {
        res.json({
          status: "success",
          code: 200,
          num: data[0]
        });
        return;
      }
    })
  });

  //$route POST /admin/disableoneadmin
  //desc   禁用某个管理员
  //access Private
  router.post('/disableoneadmin', (req, res) => {
    var indexID = req.body.indexID;
    db.query(`SELECT admin_state FROM admin_table where GUID='${indexID}'`, (err, admin_statedata) => {
      if (err) {
        res.status(500).send('数据库错误').end();
      }
      else {
        if (admin_statedata[0].admin_state == 'true') {
          db.query(`UPDATE admin_table set admin_state='false' where GUID='${indexID}'`, (err, data) => {
            if (err) {
              res.status(500).send('数据库错误').end();
            }
            else {
              res.json({
                code: 200,
                status: "success",
                message: '操作成功！'
              });
              return;
            }
          })
        } else {
          db.query(`UPDATE admin_table set admin_state='true' where GUID='${indexID}'`, (err, data) => {
            if (err) {
              res.status(500).send('数据库错误').end();
            }
            else {

              res.json({
                code: 200,
                status: "success",
                message: '操作成功！'
              });
              return;
            }
          })
        }
      }
    })
  });






  router.post('/creatrole', (req, res) => {
    console.log(req.body);
    var username = req.body.username;
    // var password = common.md5(req.body.password + common.MD5_SUFFIX);
    var roles = req.body.roles;
    var desc = req.body.desc;
    var creattime = req.body.creattime;
    var indexID = req.body.indexID;

    if (indexID) {
      //用户是否为空
      if (username == '') {
        res.json({
          code: 500,
          message: '用户名不能为空'
        });
        return;
      }
      else {
        db.query(`SELECT * FROM role_table WHERE ID='${indexID}'`, (err, data) => {
          if (err) {
            res.status(500).send('数据库错误').end();
          }
          else {
            if (data.length != 0) {
              db.query(`UPDATE role_table SET user_rolename='${username}',user_ownrole='${roles}',user_remarks='${desc}',user_state='false',user_modifytime='${creattime}' WHERE ID='${indexID}'`, (err, data) => {
                if (err) {
                  res.status(500).send('更新角色失败。').end();
                } else {
                  res.json({
                    code: 200,
                    message: '更新角色成功。'
                  });
                  return;
                }
              })
            }
            else {
              res.json({
                code: 500,
                message: '该用户不存在。'
              });
              return;
            }
          }
        })
      }
    } else {
      //用户是否为空
      if (username == '') {
        res.json({
          code: 500,
          message: '用户名不能为空'
        });
        return;
      }
      else {
        db.query(`SELECT * FROM role_table WHERE user_rolename='${username}'`, (err, data) => {
          if (err) {
            res.status(500).send('数据库错误').end();
          }
          else {
            if (data.length == 0) {
              db.query(`INSERT INTO role_table (user_rolename,user_ownrole,user_remarks,user_state,user_createtime) VALUES ('${username}','${roles}','${desc}','N','${creattime}')`, (err, data) => {
                if (err) {
                  res.status(500).send('创建角色失败。').end();
                } else {
                  res.json({
                    code: 200,
                    message: '创建角色成功。'
                  });
                  return;
                }
              })
            }
            else {
              res.json({
                code: 500,
                message: '该用户已存在。'
              });
              return;
            }
          }
        })
      }
    }

  });

  //获取某个人的角色权限信息
  router.post('/getonerole', (req, res) => {
    var indexID = req.body.indexID;
    db.query(`SELECT * FROM role_table where ID='${indexID}'`, (err, data) => {
      if (err) {
        res.status(500).send('数据库错误').end();
      }
      else {
        res.send(data).end();
      }
    })
  });

  //禁用某个角色
  router.post('/disableonerole', (req, res) => {
    var indexID = req.body.indexID;
    db.query(`SELECT user_state FROM role_table where ID='${indexID}'`, (err, user_statedata) => {
      if (err) {
        res.status(500).send('数据库错误').end();
      }
      else {
        if (user_statedata[0].user_state == 'true') {
          db.query(`UPDATE role_table set user_state='false' where ID='${indexID}'`, (err, data) => {
            if (err) {
              res.status(500).send('数据库错误').end();
            }
            else {

              res.json({
                code: 200,
                message: '操作成功！',
                data: data
              });
              return;
            }
          })
        } else {
          db.query(`UPDATE role_table set user_state='true' where ID='${indexID}'`, (err, data) => {
            if (err) {
              res.status(500).send('数据库错误').end();
            }
            else {

              res.json({
                code: 200,
                message: '操作成功！',
                data: data
              });
              return;
            }
          })
        }
      }
    })
  });

  //获取所有管理员
  router.post('/getpeople', (req, res) => {
    db.query(`SELECT * FROM admin_table`, (err, data) => {
      if (err) {
        res.status(500).send('数据库错误').end();
      }
      else {
        res.send(data).end();
      }
    })
  });

  //创建管理员
  router.post('/creatpeople', (req, res) => {
    var username = req.body.username;
    var password = common.md5(req.body.password + common.MD5_SUFFIX);
    var roles = req.body.roles;
    var desc = req.body.desc;
    var creattime = req.body.creattime;
    var indexID = req.body.indexID;
    if (indexID) {
      //用户是否为空
      if (username == '') {
        res.json({
          code: 500,
          message: '用户名不能为空'
        });
        return;
      }
      else {
        db.query(`SELECT * FROM admin_table WHERE GUID='${indexID}'`, (err, data) => {
          if (err) {
            res.status(500).send('数据库错误').end();
          }
          else {
            if (data.length != 0) {
              db.query(`UPDATE admin_table SET admin_name='${username}', password='${password}',admin_ownrole='${roles}',admin_remarks='${desc}',admin_state='false',admin_modifytime='${creattime}' WHERE GUID='${indexID}'`, (err, data) => {
                if (err) {
                  res.status(500).send('更新失败。').end();
                } else {
                  res.json({
                    code: 200,
                    message: '更新成功。'
                  });
                  return;
                }
              })
            }
            else {
              res.json({
                code: 500,
                message: '该用户不存在。'
              });
              return;
            }
          }
        })
      }
    } else {
      //用户是否为空
      if (username == '') {
        res.json({
          code: 500,
          message: '用户名不能为空'
        });
        return;
      }
      else {
        db.query(`SELECT * FROM admin_table WHERE admin_name='${username}'`, (err, data) => {
          if (err) {
            res.status(500).send('数据库错误').end();
          }
          else {
            if (data.length == 0) {
              db.query(`INSERT INTO admin_table (admin_name,password,admin_ownrole,admin_remarks,admin_state,admin_createtime) VALUES ('${username}','${password}','${roles}','${desc}','false','${creattime}')`, (err, data) => {
                if (err) {
                  res.status(500).send('创建人员失败。').end();
                } else {
                  res.json({
                    code: 200,
                    message: '创建成功。'
                  });
                  return;
                }
              })
            }
            else {
              res.json({
                code: 500,
                message: '该用户已存在。'
              });
              return;
            }
          }
        })
      }
    }
  });

  //获取某个管理员
  router.post('/getonepeople', (req, res) => {
    var indexID = req.body.indexID;
    db.query(`SELECT * FROM admin_table where GUID='${indexID}'`, (err, data) => {
      if (err) {
        res.status(500).send('数据库错误').end();
      }
      else {
        res.send(data).end();
      }
    })
  });

  //获取管理员的权限信息
  router.post('/amdinownrole', (req, res) => {
    console.log(req.body);
    var adminname = req.body.adminname;
    db.query(`SELECT r.user_ownrole FROM admin_table a,role_table r where a.admin_name='${adminname}' and r.user_rolename=a.admin_ownrole`, (err, data) => {
      if (err) {
        res.status(500).send('数据库错误').end();
      }
      else {
        res.send(data).end();
      }
    })
  });



  //禁用某个用户
  router.post('/disableuser', (req, res) => {
    var indexID = req.body.indexID;
    var state = req.body.state;
    if (state == '已禁用') {
      db.query(`UPDATE user_table SET user_state='正常' WHERE user_ID='${indexID}'`, (err, data) => {
        if (err) {
          res.status(500).send('数据库错误').end();
        }
        else {
          res.send(data).end();
        }
      })
    } else {
      db.query(`UPDATE user_table SET user_state='已禁用' WHERE user_ID='${indexID}'`, (err, data) => {
        if (err) {
          res.status(500).send('数据库错误').end();
        }
        else {
          res.send(data).end();
        }
      })
    }
  });

  //软删除某个用户
  router.post('/deluser', (req, res) => {
    var indexID = req.body.indexID;
    db.query(`UPDATE user_table SET is_del='Y' WHERE user_ID='${indexID}'`, (err, data) => {
      if (err) {
        res.status(500).send('数据库错误').end();
      }
      else {
        res.json({
          code: 200,
          message: '删除成功！'
        });
        return;
      }
    })
  });

  //批量软删除用户
  router.post('/delusers', (req, res) => {
    var indexIDs = req.body.indexIDs;
    console.log(indexIDs);
    db.query(`UPDATE user_table SET is_del = 'Y' WHERE user_ID IN (${indexIDs})`, (err, data) => {
      if (err) {
        res.status(500).send('数据库错误').end();
      }
      else {
        res.json({
          code: 200,
          message: '删除成功！'
        });
        return;
      }
    })
  });

  //用户管理的搜索结果
  router.post('/findsearchresult', (req, res) => {
    var state = req.body.state;
    var mainwords = req.body.mainwords;
    db.query(`SELECT * FROM user_table where user_state='${state}' OR user_nickname LIKE '%${mainwords}%' OR user_phone LIKE '%${mainwords}%' limit ${100}; `, (err, data) => {
      if (err) {
        res.status(500).send('数据库错误').end();
      }
      else {
        res.send(data).end();
      }
    })
  });



  return router;
}